package com.xt.wikiperfumapi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xt.wikiperfumapi.model.UserInfo;
import com.xt.wikiperfumapi.service.impl.UserInfoServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * UserDetailsService的实现类
 *
 * @author 24862
 */
@Service
@Slf4j
public class AuthUserDetailService implements UserDetailsService {


    @Resource
    UserInfoServiceImpl userInfoService;

    /**
     * 这一层必须采用username+password
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            if (username == null) {
                throw new UsernameNotFoundException("用户名不能为空");
            }
            if (userInfoService.count(new QueryWrapper<UserInfo>()
                    .eq("username", username)
                    .eq("is_enabled",1)
                    .eq("is_deleted",0))==0) {
                throw new UsernameNotFoundException("username password state error");
            }
            UserInfo userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>()
                    .eq("username", username)
                    .eq("is_enabled",1)
                    .eq("is_deleted",0)
            );
            UserInfo userExtendDetails = new UserInfo();
            userExtendDetails.setUsername(userInfo.getUsername());
            userExtendDetails.setPassword(userInfo.getPassword());
            userExtendDetails.setRoles(userInfo.getRoles());//直接用角色来定义权限，权限是特殊的角色
            userExtendDetails.setIsEnabled(userInfo.getIsEnabled());//是否可用  1
            userExtendDetails.setIsDeleted(userInfo.getIsDeleted());//是否删除  0
            return userExtendDetails;
        }catch (Exception e){
            log.info(e.getMessage());
            throw new UsernameNotFoundException("server error");
        }
    }

}
